﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VigenereMeter
{
    class Vigenere
    {
        public static byte nAlphabet = 26;

        public static string Encrypt(string plainText, string key)
        {
            StringBuilder cipherText = new StringBuilder();
            int length = plainText.Length;
            int keyLength = key.Length;
            byte plainChar;
            byte keyChar;

            // Make upper case
            plainText = plainText.ToUpper();
            key = key.ToUpper();

            for (int i = 0; i < length; ++i)
            {
                plainChar = (byte)plainText[i];
                keyChar = (byte)key[i % keyLength];

                if (plainChar >= (byte)'A' && plainChar <= (byte)'Z'
                    && keyChar >= (byte)'A' && keyChar <= (byte)'Z')
                {
                    keyChar -= (byte)'A';
                    plainChar -= (byte)'A';

                    plainChar += (byte)keyChar;
                    plainChar %= nAlphabet;
                    plainChar += (byte)'A';
                }

                cipherText.Append((char)plainChar);
            }

            return cipherText.ToString();
        }

        public static string Decrypt(string cipherText, string key)
        {
            StringBuilder plainText = new StringBuilder();
            int length = cipherText.Length;
            int keyLength = key.Length;
            byte cipherChar;
            byte keyChar;

            // Make upper case
            cipherText = cipherText.ToUpper();
            key = key.ToUpper();

            for (int i = 0; i < length; ++i)
            {
                cipherChar = (byte)cipherText[i];
                keyChar = (byte)key[i % keyLength];

                if (cipherChar >= (byte)'A' && cipherChar <= (byte)'Z'
                    && keyChar >= (byte)'A' && keyChar <= (byte)'Z')
                {
                    keyChar -= (byte)'A';
                    cipherChar -= (byte)'A';

                    cipherChar = (byte)(((int)nAlphabet + (int)cipherChar - (int)keyChar) % (int)nAlphabet);
                    cipherChar += (byte)'A';
                }

                plainText.Append((char)cipherChar);
            }

            return plainText.ToString();
        }
    }
}